package io.terminus.spzx.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.terminus.spzx.common.config.exception.SpzxCustomException;
import io.terminus.spzx.feign.cart.CartFeignClient;
import io.terminus.spzx.feign.product.ProductFeignClient;
import io.terminus.spzx.feign.user.UserFeignClient;
import io.terminus.spzx.model.dto.h5.OrderInfoDto;
import io.terminus.spzx.model.entity.h5.CartInfo;
import io.terminus.spzx.model.entity.order.OrderInfo;
import io.terminus.spzx.model.entity.order.OrderItem;
import io.terminus.spzx.model.entity.order.OrderLog;
import io.terminus.spzx.model.entity.product.ProductSku;
import io.terminus.spzx.model.entity.user.UserAddress;
import io.terminus.spzx.model.entity.user.UserInfo;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import io.terminus.spzx.model.vo.h5.TradeVo;
import io.terminus.spzx.order.mapper.OrderItemMapper;
import io.terminus.spzx.order.mapper.OrderLogMapper;
import io.terminus.spzx.order.mapper.OrderMapper;
import io.terminus.spzx.order.service.OrderService;
import io.terminus.spzx.utils.AuthContextUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 【移动端】订单管理Service实现类
 * @Date 2024-12-08
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final CartFeignClient cartFeignClient;

    private final ProductFeignClient productFeignClient;

    private final UserFeignClient userFeignClient;

    private final OrderMapper orderMapper;

    private final OrderItemMapper orderItemMapper;

    private final OrderLogMapper orderLogMapper;

    @Override
    public TradeVo getTrade() {
        TradeVo tradeVo = new TradeVo();

        // 获取购物车中的商品列表
        List<CartInfo> checkedCartInfoList = cartFeignClient.getAllChecked();

        // 将购物项数据转换成功订单明细数据
        List<OrderItem> orderItemList = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CartInfo cartInfo : checkedCartInfoList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            // 计算购物车结算的总金额
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));

            orderItemList.add(orderItem);
        }
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);

        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
        }

        for (OrderItem orderItem : orderItemList) {
            ProductSku productSku = productFeignClient.getBySkuId(orderItem.getSkuId());
            if (Objects.isNull(productSku)) {
                throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
            }
            // TODO 校验库存: productFeignClient.getBySkuId中没有查询库存字段
            if (orderItem.getSkuNum() > productSku.getStockNum()) {
                throw new SpzxCustomException(ResultCodeEnum.STOCK_LESS);
            }
        }

        OrderInfo orderInfo = new OrderInfo();
        // 订单编号
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        // 用户id
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        orderInfo.setUserId(userInfo.getId());
        // 用户昵称
        orderInfo.setNickName(userInfo.getNickName());
        // 用户收货地址信息
        UserAddress userAddress = userFeignClient.getUserAddress(orderInfoDto.getUserAddressId());
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        // 订单金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setPayType(2);
        orderInfo.setOrderStatus(0);

        orderMapper.save(orderInfo);

        // 保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.save(orderItem);
        }

        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.save(orderLog);

        // 删除购物车数据
        cartFeignClient.deleteChecked();

        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        return orderMapper.getById(orderId);
    }

    @Override
    public TradeVo buy(Long skuId) {
        TradeVo tradeVo = new TradeVo();
        // 查询商品
        ProductSku productSku = productFeignClient.getBySkuId(skuId);
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);
        tradeVo.setOrderItemList(orderItemList);

        // 计算总金额
        BigDecimal totalAmount = productSku.getSalePrice();
        tradeVo.setTotalAmount(totalAmount);

        return tradeVo;
    }

    @Override
    public PageInfo<OrderInfo> findUserPage(Integer page, Integer limit, Integer orderStatus) {
        PageHelper.startPage(page, limit);
        Long userId = AuthContextUtil.getUserId();
        List<OrderInfo> orderInfoList = orderMapper.findUserPage(userId, orderStatus);

        orderInfoList.forEach(orderInfo -> {
            List<OrderItem> orderItem = orderItemMapper.findByOrderId(orderInfo.getId());
            orderInfo.setOrderItemList(orderItem);
        });

        return new PageInfo<>(orderInfoList);
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderMapper.getByOrderNo(orderNo);
        List<OrderItem> orderItem = orderItemMapper.findByOrderId(orderInfo.getId());
        orderInfo.setOrderItemList(orderItem);

        return orderInfo;
    }

    @Override
    public void updateOrderStatus(String orderNo, Integer orderStatus) {
        // 更新订单状态
        OrderInfo orderInfo = orderMapper.getByOrderNo(orderNo);
        orderInfo.setOrderStatus(1);
        orderInfo.setPayType(orderStatus);
        orderInfo.setPaymentTime(new Date());
        orderMapper.updateById(orderInfo);

        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(1);
        orderLog.setNote("支付宝支付成功");
        orderLogMapper.save(orderLog);
    }
}
